import { useState, useEffect } from "react";
import { Editor, Viewer } from '@bytemd/react'
import { Button, Card, message, Popconfirm, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons';
import Menu from './menu'
import gfm from '@bytemd/plugin-gfm'
import zh from 'bytemd/lib/locales/zh_Hans.json'
import('bytemd/dist/index.min.css')
const plugins = [
    gfm(),
]



export default () => {
    const [id, setId] = useState(null)
    const [value, setValue] = useState('')
    const [title, setTitle] = useState('')
    const [date, setDate] = useState(new Date().toLocaleDateString())
    const [edit, setEdit] = useState(true)
    const [list, setList] = useState([])

    useEffect(() => {
        db.articles.toArray().then(res => {
            setList(res)
        })
        window.addEventListener('keydown', function (e) {
            if (e.altKey && e.key == 'o') {
                Modal.confirm({
                    title: '您是否想要删除全部文档?',
                    icon: <ExclamationCircleOutlined />,
                    content: '点击确定删除全部文档，文档将丢失！',
                    onOk: () => {
                        db.delete();
                        setTimeout(()=> {
                            location.reload()
                        }, 100)
                    },
                    onCancel() {
                        console.log('Cancel');
                    },
                })
            }
        })
    }, [])

    const readContent = t => {
        setValue(t.content || '')
        setTitle(t.title || '')
        setId(t.id)
        setEdit(false)
    }

    const newArt = () => {
        setValue('')
        setTitle('')
        setId(null)
        setEdit(true)
    }

    const save = () => {
        if (id) {
            db.articles.put({
                title,
                date,
                content: value,
                id: id
            }).then(res => {
                message.success('保存成功！')
                setEdit(false);
            })
        } else {
            db.articles.add({
                title,
                date,
                content: value
            }).then(res => {
                message.success('保存成功！')
                setEdit(false);
            })
        }
        db.articles.toArray().then(res => {
            setList(res)
        })
    }

    const Del = () => {
        db.articles.delete(id).then(() => {
            db.articles.toArray().then(res => {
                setList(res)
            })
            message.success('删除成功！')
            newArt()
        })
    }

    return (
        <div className="editor">
            <div className="editor-left">
                <Card>
                    <Menu
                        list={list}
                        read={readContent}
                        create={newArt}
                    />
                </Card>
            </div>
            <div className="editor-right">
                <Card>
                    {edit ?
                        <div className="editor-right-status">
                            <input maxLength="30" type="text" placeholder="请输入标题..." value={title} onChange={e => setTitle(e.target.value)} />
                            {id && <Popconfirm
                                title="确定删除这条？?"
                                onConfirm={Del}
                                okType="danger"
                                okText="确定"
                                cancelText="取消"
                            >
                                <Button danger type="text" >删除</Button>
                            </Popconfirm>}
                            <Button type="link" onClick={() => save()}>保存</Button>
                        </div> :
                        <div className="editor-right-status">
                            <p>{title || '未命名'}</p>
                            <Button type="link" onClick={() => setEdit(true)}>编辑</Button>
                        </div>
                    }
                    {
                        edit ? <Editor
                            mode="auto"
                            locale={zh}
                            value={value}
                            plugins={plugins}
                            height="500px"
                            onChange={(v) => {
                                setValue(v)
                            }}
                        /> :
                            <Viewer value={value} />
                    }
                </Card>
            </div>
        </div>
    )
}